package mashibing.sort;

/**
 * 选择排序
 */
public class Code1SelectionSort {
    public static int[] selectionSort(int arr[]){
        if (arr == null || arr.length < 2){
            return arr;
        }
        // 0 ~ N-1找到最小值放到0位置上
        // 1 ~ N-1找到最小值放到1位置上
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i+1; j < arr.length; j++) {
                minIndex = arr[j] < arr[minIndex] ? j : minIndex;
            }
            swap(arr,i,minIndex);
        }
        return arr;
    }

    private static void swap(int[] arr, int i, int minIndex) {
        int temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }

    public static void print(int arr[]){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+",");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr = new int[]{23,45,24,69,89,34,56,67};
        print(arr);
        int[] arr2 = selectionSort(arr);
        print(arr2);

    }
}
